<template>
	<div class="content">
		<cl-crud @load="onLoad">
			<template #slot-top>
				<div class="bi-filter">
					<div
						class="bi-li"
						:class="[{ active: selects.isOpened === 0 }]"
						@click="changeStatus(0)"
					>
						进行中拼团
					</div>
					<div
						class="bi-li"
						:class="[{ active: selects.isOpened === 1 }]"
						@click="changeStatus(1)"
					>
						历史拼团
					</div>
				</div>
			</template>
			<template #slot-btn>
				<el-button type="primary" size="mini" @click="$refs.elDig.open('add')"
					>添加</el-button
				>
				<el-button
					type="success"
					size="mini"
					@click="batchFiled()"
					:disabled="selectRow.length > 0 ? false : true"
					>批量开团</el-button
				>
			</template>
			<template #slot-filter>
				<div class="filter-list">
					<div class="filter-item">
						<span class="filter-title">分类：</span>
						<el-select
							size="mini"
							filterable
							placeholder="请选择分类"
							style="width: 140px"
							v-model="selects.firstClassify"
							@change="val => onClassifyChange(val, 'first')"
						>
							<el-option value label="全部"></el-option>
							<el-option
								:label="item.name"
								:value="item.id"
								v-for="item in options.firstClassify"
								:key="item.id"
							></el-option>
						</el-select>
					</div>
					<!--                    <div class="filter-item">-->
					<!--                        <span class="filter-title">二级分类：</span>-->
					<!--                        <el-select-->
					<!--                                class="filter-select"-->
					<!--                                size="mini"-->
					<!--                                filterable-->
					<!--                                placeholder="请选择二级分类"-->
					<!--                                style="width: 140px"-->
					<!--                                v-model="selects.secondClassify"-->
					<!--                                @change="val => onClassifyChange(val)"-->
					<!--                        >-->
					<!--                            <el-option :label="item.name" :value="item.id" v-for="item in options.secondClassify" :key="item.id"></el-option>-->
					<!--                        </el-select>-->
					<!--                    </div>-->
					<!--                    <div class="filter-item">-->
					<!--                        <span class="filter-title">库存：</span>-->
					<!--                        <el-input-number-->
					<!--                                v-model="selects.startSales"-->
					<!--                                controls-position="right"-->
					<!--                                style="width:80px;"-->
					<!--                                size="mini"-->
					<!--                        ></el-input-number>-->
					<!--                        <span style="font-size:16px;margin-right:0px"> - </span>-->
					<!--                        <el-input-number-->
					<!--                                v-model="selects.endSales"-->
					<!--                                controls-position="right"-->
					<!--                                style="width:80px;"-->
					<!--                                size="mini"-->
					<!--                        ></el-input-number>-->
					<!--                    </div>-->
					<div class="filter-item">
						<span class="filter-title">价格：</span>
						<el-input-number
							v-model="selects.startPrice"
							controls-position="right"
							style="width:80px;"
							size="mini"
						></el-input-number>
						<span style="font-size:16px;margin-right:0px"> - </span>
						<el-input-number
							v-model="selects.endPrice"
							controls-position="right"
							style="width:80px;"
							size="mini"
						></el-input-number>
						<el-button style="margin-left:1em" size="mini" @click="onSearch()"
							>搜索</el-button
						>
						<el-button style="margin-left:1em" size="mini" @click="resetSearch()"
							>重置</el-button
						>
					</div>
				</div>
			</template>
			<template #slot-time>
				<div class="filter-item">
					<span class="filter-title" style="font-size: 14px">创建时间：</span>
					<el-radio-group
						class="time-group"
						v-model="selects.createTime"
						size="mini"
						@change="onCreateTimeChange"
					>
						<el-radio-button label="今天"></el-radio-button>
						<el-radio-button label="昨天"></el-radio-button>
						<el-radio-button label="最近7天"></el-radio-button>
						<el-radio-button label="最近30天"></el-radio-button>
						<el-radio-button label="本月"></el-radio-button>
						<el-radio-button label="全部"></el-radio-button>
					</el-radio-group>
				</div>
			</template>

			<template #table-column-goodsInfo="{ scope }">
				<div class="goods-info">
					<img :src="scope.row.pic" />
					<div class="goods-content">
						<p>{{ scope.row.title }}</p>
						<p class="price">
							售价：<span>{{ scope.row.groupPrice }}</span>
						</p>
						<!--                        <p class="sort">分类：<span>{{ scope.row.price }}</span></p>-->
					</div>
				</div>
			</template>
			<!--            <template #table-column-isOpened="{ scope }">-->
			<!--                <el-switch v-model="scope.row.isOpened" active-text="上架"  inactive-text="下架" :active-value="1" :inactive-value="0" @change="(e) => onSwitchChange(e, scope.row)"></el-switch>-->
			<!--            </template>-->

			<template #slot-operate="{ scope }">
				<el-button type="text" size="small" @click="$refs.elDig.open('edit', scope.row)"
					>编辑</el-button
				>
				<el-button type="text" size="small" @click="groupDetail(scope.row)">查看</el-button>
				<el-button
					type="text"
					size="small"
					@click="onGroupNow(scope.row)"
					v-if="scope.row.isOpened === 0"
					>立即开团</el-button
				>
			</template>
		</cl-crud>

		<cl-form ref="cl-form"></cl-form>

		<el-dig ref="elDig" @refresh="crud.refresh()"></el-dig>
	</div>
</template>

<script>
import moment from 'moment';
import ElDig from './components/ElDig';
import GoodsInfo from './components/GoodsInfo';
import GroupDetail from './components/GroupDetail';
export default {
	name: 'banner',
	components: {
		ElDig
	},
	data() {
		return {
			crud: null,
			options: {
				firstClassify: [],
				secondClassify: []
			},
			selects: {
				isOpened: 0,
				firstClassify: '',
				createTime: '今天'
			},
			selectRow: []
		};
	},
	created() {
		// 获取一级分类
		this.$service.goods.classify
			.list({
				parentId: 0
			})
			.then(res => {
				this.options.firstClassify = res;
			});
	},
	methods: {
		onLoad({ ctx, app }) {
			this.crud = app;
			let that = this;
			ctx.service(this.$service.group.goodsCombination)
				.set('search', {
					key: {
						placeholder: '请输入商品标题'
					}
				})
				.set('table', {
					columns: [
						{
							type: 'selection',
							label: '全选',
							align: 'center',
							width: '60px'
						},
						{
							label: '拼团ID',
							prop: 'id',
							align: 'center',
							width: 100
						},
						{
							label: '拼团商品',
							prop: 'goodsInfo',
							align: 'left',
							width: 350
						},
						{
							label: '开团人数（已参团）',
							prop: 'alreadyGroupUserNumber',
							align: 'center'
						},
						{
							label: '开团机器人',
							prop: 'groupRobotUserNumber',
							align: 'center'
						},
						{
							label: '开始时间',
							prop: 'startTime',
							align: 'center'
						},
						{
							label: '结束时间',
							prop: 'endTime',
							align: 'center'
						},
						{
							label: '创建时间',
							prop: 'createTime',
							align: 'center',
							sortable: 'custom'
						},
						{
							label: '排序',
							prop: 'level',
							align: 'center',
							sortable: 'custom'
						},
						{
							label: '状态',
							prop: 'isOpened',
							align: 'center',
							dict: [
								{
									label: '进行中',
									value: 0
								},
								{
									label: '已开团',
									value: 1
								}
							]
						}
					],
					op: {
						layout: ['slot-operate']
					},
					props: {
						'default-sort': {
							prop: 'createTime',
							order: 'descending'
						}
					},
					on: {
						'selection-change': selection => {
							this.selectRow = selection;
						}
					}
				})
				.set('upsert', {
					props: {
						title: '',
						width: '950px',
						labelWidth: '130px'
					},
					items: [
						{
							prop: 'goodsId',
							label: '商品ID：',
							span: 14,
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请填写商品ID',
									clearable: true
								}
							},
							rules: [
								{
									required: true,
									message: '商品ID不能为空'
								}
							]
						},
						{
							span: 6,
							prop: 'search',
							component: {
								name: 'search',
								methods: {
									checkGoods() {
										let goodsId = app.getData('upsert.form.goodsId');
										if (!goodsId) return false;
										that.$service.goods.manage
											.info({
												id: goodsId
											})
											.then(res => {
												app.setData('upsert.form.goodsInfo', res);
												if (res.title) {
													app.setData(
														'upsert.items[prop:goodsInfo].hidden',
														false
													);
												} else {
													app.setData(
														'upsert.items[prop:goodsInfo].hidden',
														true
													);
												}
											})
											.catch(() => {
												that.$message.error('未检索到商品');
												app.setData(
													'upsert.items[prop:goodsInfo].hidden',
													true
												);
											});
									}
								},
								render() {
									return (
										<div style="margin-left: -120px">
											<el-button
												type="primary"
												size="small"
												on-click={this.checkGoods}>
												检索
											</el-button>
										</div>
									);
								}
							}
						},
						{
							hidden: true,
							prop: 'goodsInfo',
							label: '商品信息：',
							component: GoodsInfo
						},
						{
							prop: 'groupUserNumber',
							label: '开团人数：',
							span: 12,
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请填写开团人数',
									clearable: true
								}
							},
							rules: {
								required: true,
								message: '开团人数不能为空'
							}
						},
						{
							prop: 'groupRobotUserNumber',
							label: '开团机器人数：',
							span: 12,
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请填写开团机器人数',
									clearable: true
								}
							}
						},
						{
							prop: 'time',
							label: '拼团时间：',
							span: 12,
							component: {
								name: 'el-date-picker',
								attrs: {
									type: 'datetimerange',
									'value-format': 'yyyy-MM-dd HH:mm:ss',
									'start-placeholder': '开始日期',
									'end-placeholder': '结束日期'
								}
							},
							rules: {
								required: true,
								message: '请选择拼团开始时间'
							}
						},
						{
							prop: 'profitRate',
							label: '拼团让利%：',
							span: 12,
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请填写拼团让利',
									clearable: true
								}
							},
							rules: {
								required: true,
								message: '拼团让利不能为空'
							}
						},
						{
							prop: 'level',
							label: '排序：',
							value: 0,
							span: 12,
							component: {
								name: 'el-input-number',
								attrs: {
									placeholder: '请输入排序',
									clearable: true
								}
							},
							rules: [
								{
									required: true,
									message: '排序不能为空'
								}
							]
						},
						{
							prop: 'newPerson',
							label: '是否新人专享：',
							value: 0,
							component: {
								name: 'el-radio-group',
								options: [
									{
										label: '否',
										value: 0
									},
									{
										label: '是',
										value: 1
									}
								]
							},
							rules: {
								required: true,
								message: '新人专享状态不能为空'
							}
						}
					]
				})
				.set('layout', [
					['slot-top'],
					['refresh-btn', 'slot-btn', 'slot-filter', 'flex1', 'search-key'],
					['slot-time'],
					['data-table'],
					['flex1', 'pagination']
				])
				.on('open', (isEdit, form) => {
					app.setData('upsert.items[prop:goodsInfo].hidden', true);
					if (isEdit) {
						app.setData('upsert.props.title', '编辑商品');
						app.setForm('classifyIds', form.classifyIds.split(','));

						app.setForm('time', [
							moment(parseInt(form.startTime)).format('YYYY-MM-DD HH:mm:ss'),
							moment(parseInt(form.endTime)).format('YYYY-MM-DD HH:mm:ss')
						]);
					} else {
						app.setData('upsert.props.title', '新增商品');
					}
				})
				.on('submit', (isEdit, data, { next, done }) => {
					if (!data.goodsInfo) {
						this.$message.error('请先检索商品');
						done();
						return false;
					}
					if (parseInt(data.stock) === 0) {
						this.$message.error('库存不足');
						done();
						return false;
					}
					// 让利比例不正确
					if (parseFloat(data.profitRate) >= 0 && parseFloat(data.profitRate) <= 100) {
						next({
							...data,
							startTime: data.time[0],
							endTime: data.time[1],
							groupPrice: data.goodsInfo.endprice,
							costprice: data.costprice
						});
					} else {
						this.$message.error('请输入正确的让利比例');
						done();
						return false;
					}
				})
				.on('refresh', async (params, { next, render }) => {
					const { list } = await next(params);
					list.forEach(item => {
						item.startTime = moment(parseInt(item.startTime)).format(
							'YYYY-MM-DD HH:mm:ss'
						);
						item.endTime = moment(parseInt(item.endTime)).format('YYYY-MM-DD HH:mm:ss');
					});
					render(list);
				})
				.done();
			let params = {};
			if (this.selects.createTime === '今天') {
				params.startTime = moment().format('YYYY-MM-DD 00:00:00');
				params.endTime = moment().format('YYYY-MM-DD 23:59:59');
			}
			app.refresh({
				isOpened: 0,
				status: 0,
				...params
			});
		},
		refresh(params) {
			this.crud.refresh(params);
		},
		// 分类筛选
		onClassifyChange(val, level) {
			this.refresh({
				classifyId: val,
				page: 1
			});
			if (level === 'first') {
				// 获取二级分类
				this.$service.goods.classify
					.list({
						parentId: val
					})
					.then(res => {
						this.options.secondClassify = res;
					});
			}
		},
		changeStatus(active) {
			if (this.selects.isOpened === active) {
				return false;
			}
			this.selects.isOpened = active;
			this.refresh({
				isOpened: active,
				status: active
			});
		},
		addGroup() {
			this.$refs.elDig.open();
		},
		// 批量操作
		batchFiled() {
			let idsArr = [];
			this.selectRow.forEach(item => {
				idsArr.push(item.id);
			});

			this.$confirm('立即开团将自动补充机器人', '您确定要立即开团吗？', {
				confirmButtonText: '立即开团',
				cancelButtonText: '考虑一下',
				type: 'warning'
			}).then(() => {
				this.$service.group.goodsCombination
					.lotteryResult({
						ids: idsArr.join(',')
					})
					.then(() => {
						this.$message.success('开团成功');
						this.crud.refresh();
					})
					.catch(err => {
						this.$message.error(err);
					});
			});
		},
		onSwitchChange(e, item) {
			this.$service.group.goodsCombination
				.update({
					id: item.id,
					status: e
				})
				.then(() => {
					this.crud.refresh();
				})
				.catch(err => {
					this.$message.error(err);
				});
		},
		onSearch() {
			this.crud.refresh({
				startSales: this.selects.startSales,
				endSales: this.selects.endSales,
				startPrice: this.selects.startPrice,
				endPrice: this.selects.endPrice
			});
		},
		resetSearch() {
			this.selects.firstClassify = '';
			this.selects.startSales = '';
			this.selects.endSales = '';
			this.selects.startPrice = '';
			this.selects.endPrice = '';

			this.crud.refresh({
				classifyId: '',
				startSales: null,
				endSales: null,
				startPrice: null,
				endPrice: null
			});
		},
		groupDetail(item) {
			this.$refs['cl-form'].open({
				props: {
					title: '拼团详情',
					width: '850px',
					showClose: false,
					'label-width': '0px'
				},
				items: [
					{
						prop: 'groupDetail',
						value: item,
						component: GroupDetail
					}
				],
				op: {
					visible: false
				}
			});
		},
		onGroupNow(item) {
			this.$confirm('立即开团将自动补充机器人', '您确定要立即开团吗？', {
				confirmButtonText: '立即开团',
				cancelButtonText: '考虑一下',
				type: 'warning'
			}).then(() => {
				this.$service.group.goodsCombination
					.lotteryResult({
						ids: item.id
					})
					.then(() => {
						this.$message.success('开团成功');
						this.crud.refresh();
					})
					.catch(err => {
						this.$message.error(err);
					});
			});
		},
		onCreateTimeChange(val) {
			let params = {};
			if (val === '今天') {
				params.startTime = moment().format('YYYY-MM-DD 00:00:00');
				params.endTime = moment().format('YYYY-MM-DD 23:59:59');
			}
			if (val === '昨天') {
				params.startTime = moment(new Date())
					.add(-1, 'days')
					.format('YYYY-MM-DD 00:00:00');
				params.endTime = moment(new Date())
					.add(-1, 'days')
					.format('YYYY-MM-DD 23:59:59');
			}
			if (val === '最近7天') {
				params.startTime = moment(new Date())
					.add(-6, 'days')
					.format('YYYY-MM-DD 00:00:00');
				params.endTime = moment(new Date()).format('YYYY-MM-DD 23:59:59');
			}
			if (val === '最近30天') {
				params.startTime = moment(new Date())
					.add(-29, 'days')
					.format('YYYY-MM-DD 00:00:00');
				params.endTime = moment(new Date()).format('YYYY-MM-DD 23:59:59');
			}
			if (val === '本月') {
				params.startTime = moment(
					moment()
						.month(moment().month())
						.startOf('month')
						.valueOf()
				).format('YYYY-MM-DD 00:00:00');
				params.endTime = moment().format('YYYY-MM-DD 23:59:59');
			}
			if (val === '全部') {
				params.startTime = null;
				params.endTime = null;
			}
			this.refresh(params);
		}
	}
};
</script>

<style lang="stylus" scoped>
.content {
    .goods-info {
        flexBox(space-between, flex-start)
        img {
            width: 80px;
            height: 80px;
            margin-right 10px
        }
        .goods-content {
            flex: 1;
            .price {
                span {
                    color: $main-color
                }
            }
        }
    }
}
/deep/.time-group {
	.el-radio-button {
		margin-right 10px;
		.el-radio-button__inner {
			border 1px solid #DCDFE6
			border-radius 4px
			box-shadow: 0 0 0
		}
	}
}
</style>
